package pers.cz.javacvdemo.oss.service;

import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jmx.MBeanServerNotFoundException;
import pers.cz.javacvdemo.oss.model.QueueDataWrapper;
import pers.cz.javacvdemo.redis.RedisService;
import pers.cz.javacvdemo.utils.HlsUtils;
import pers.cz.javacvdemo.utils.JefFileUtils;
import pers.cz.javacvdemo.utils.SpringContext;
import pers.cz.javacvdemo.video.Resolution;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;

/**
 * @version 1.0
 * @description: 队列消费者
 * @author: ChengZhi 0336
 * @create: 2025-08-14 14:07
 **/
@Slf4j
public class BucketEventHandler implements WorkHandler<QueueDataWrapper> {

	@Override
	public void onEvent(QueueDataWrapper queueData) throws IOException {

		if (queueData == null || queueData.getKey() == null) {
			log.warn("接收到无效事件数据");
			return;
		}

		log.info("开始处理事件" + queueData.getKey());

		// 下载文件
		try {
			OssTemplate ossTemplate = SpringContext.getBean(OssTemplate.class);
			if (ossTemplate == null) {
				throw new MBeanServerNotFoundException("找不到OssTemplate实例");
			}
			String bucketName = queueData.getEventRecord().getRecords().get(0).getS3().getBucket().getName();
			String objectName = queueData.getEventRecord().getRecords().get(0).getS3().getObject().getKey();
			List<Resolution> resolutions = List.of(
					new Resolution(720, 1280, "720P"),
					new Resolution(480, 640, "480P"),
					new Resolution(240, 320, "240P"));
			try (InputStream inputStream = ossTemplate.getObjectAsInputStream(bucketName, objectName)) {
				HlsUtils.processVideoWithFFmpeg(objectName, inputStream, resolutions);
				uploadDealedFiles(resolutions, bucketName, objectName, ossTemplate);
			}
		} catch (Exception e) {
			log.error("处理事件失败", e);
			handleFailure(queueData);
		}
	}

	private void handleFailure(QueueDataWrapper queueData) {
		RedisService redisService = SpringContext.getBean(RedisService.class);
		if (redisService == null) {
			log.error("RedisService 未找到，无法记录失败事件");
			return;
		}
		redisService.HASH.hSet("fail-events", queueData.getKey(), queueData.getEventRecord());
		log.info("记录失败事件完成！");
	}

	/**
	 * 将处理后的文件上传到oss
	 * @param resolutions
	 * @param bucketName
	 * @param objectName
	 */
	private void uploadDealedFiles(List<Resolution> resolutions, String bucketName, String objectName, OssTemplate ossTemplate) {

		if (CollectionUtils.isEmpty(resolutions)) {
			return;
		}
		String outputFilePath = FileUtils.getTempDirectoryPath();
		for (Resolution resolution : resolutions) {
			// 上传段文件
			Collection<File> segmentFiles = JefFileUtils.getFilesByPrefix(outputFilePath, resolution.getResolutionString());
			// 上传m3u8文件
			File m3u8File = new File(outputFilePath + "/" + StringUtils.split(objectName, ".")[0] + "_" +  resolution.getResolutionString() + ".m3u8");
			segmentFiles.add(m3u8File);
			ossTemplate.putFilesAndDeleteSource(bucketName, segmentFiles);
		}
	}
}
